package com.example.arithmeticleetcode.leetcode.jan;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2021-01-08 09:25
 **/
public class Demo07 {

    public void rotate(int[] nums, int k) {
        if (nums == null || nums.length == 0) return;
        int mod = k > nums.length ? k % nums.length : k;

        for (int i = 0; i < k; i++) {
            for (int j = nums.length - 1; j > 0; j--) {
                int temp = nums[j];
                nums[j] = nums[j - 1];
                nums[j - 1] = temp;
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7};
        rotate2(nums, 3);
        List<Integer> list = new ArrayList<>();
        list.add(11026);
        System.out.println(list);
    }

    public static void rotate2(int[] nums, int k) {
        if (nums == null || nums.length == 0) return;
        int mod = k > nums.length ? k % nums.length : k;
        if (mod == 0) return;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = mod + 1; i < nums.length; i++) {
            stringBuilder.append(nums[i]);
        }
        for (int i = 0; i <= mod; i++) {
            stringBuilder.append(nums[i]);
        }
        for (int i = 0; i < nums.length; i++) {
            nums[i] = Integer.valueOf(stringBuilder.charAt(i));
        }
    }

    public static void rotate3(int[] nums, int k) {
        int n = nums.length;
        int[] newArr = new int[n];
        for (int i = 0; i < n; i++) {
            newArr[(i + k) % n] = nums[i];
        }
        System.arraycopy(newArr, 0, nums, 0, n);
    }

    public void rotate4(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }

    private void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start++] = nums[end];
            nums[end--] = temp;
        }
    }
}
